// 微信API封装
const apiPkg = {
  // 显示消息提示框
  _toast (title, time) {
    return new Promise((resolve, reject) => {
      wx.showToast({
        title,
        icon: 'none',
        duration: time || 3000,
      })
      let timer = setTimeout(() => {
        resolve()
        clearTimeout(timer)
      }, time || 3000);
    })
  },

  /*231227 yan 增加获取定位*/
  _getLocation (isShowLoading = true) {
    return new Promise((resolve, reject) => {
      if (isShowLoading) wx.showLoading({ title: '正在检测定位服务', mask: true })
      apiPkg._checkOpenSetting()
        .then(() => {
          if (isShowLoading) wx.showLoading({ title: '正在获取定位', mask: true })
          let _locationChangeFn = (res) => {
            wx.hideLoading();
            resolve(res) // 回传地里位置信息
            wx.offLocationChange(_locationChangeFn) // 关闭实时定位
            wx.stopLocationUpdate(_locationChangeFn); // 关闭监听 不关闭监听的话，有时获取位置时会非常慢
          }
          wx.startLocationUpdate({
            success: (res) => {
              wx.onLocationChange(_locationChangeFn)
            },
            fail: (err) => {
              wx.showModal({
                title: '定位服务未打开',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                confirmText: '去开启',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting({
                      success (res) {
                        res.authSetting = {
                          "scope.userLocation": true
                        }
                      }
                    });
                  }
                },
              });
              reject(err)
            }
          })
        })
        .catch(reject)
    })
  },
  //  获取当前位置
  wxLocation () {
    // _getLocation(){
    console.log('无网络定位');
    return new Promise(resolve => {
      // resolve({latitude:23.035508897569443 , longitude:113.11290771484374});
      wx.getLocation({
        type: 'gcj02', // 比较精确
        success: (res) => {
          console.log('无网络定位', res);
          resolve(res);
        },
        fail: (err) => {
          console.log('wx.getLocation:fail', err)
        }
      })
    })
  },
  /*
  * 1、检查手机系统设置是否开启定位权限
  * 2、获取小程序定位权限scope.userLocation
  * 3、未有授权通过获取定位api，弹出授权框
  * 4、授权失败提示打开小程序设置
  * */
  _checkOpenSetting () {
    return new Promise((resolve, reject) => {
      const systemSetting = wx.getSystemSetting();
      console.log(systemSetting);
      console.log(systemSetting.locationEnabled === false);
      if (!systemSetting.locationEnabled) {

        wx.showModal({
          title: '定位服务未打开',
          content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
          confirmText: '确定',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({ url: '/SlagCar/OpenLocationGuide/OpenLocationGuide' })
              reject();
            }
          },
        });
        return
      }
      wx.getSetting({
        success (res) {
          console.log(111, res);
          if (!res.authSetting['scope.userLocation']) {
            wx.getLocation({
              type: 'gcj02', // 比较精确
              success: (res) => {
                console.log(222, res);
                resolve()
              },
              fail: (res) => {
                wx.showModal({
                  title: '定位服务未打开',
                  content: '请在小程序设置中打开位置授权，以便我们为您提供更好的服务',
                  confirmText: '去开启',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting({
                        success (res) {
                          res.authSetting = {
                            "scope.userLocation": true
                          }
                        }
                      });
                    }
                  },
                });
                reject();
              }
            })
          } else { resolve() }
        }

        ,
      })
    })
  }
};

/**
 * 循环封装
 * @param object  对象或数组
 * @param fn  回调函数
 */
function each (object, fn) {
  let isArr = Array.isArray(object);
  let flag = true;
  if (isArr) {
    for (let i = 0; i < object.length; i++) {
      flag = fn && fn(i, object[i]);
      if (flag === false) return;
    }
    return
  }
  for (let k in object) {
    flag = fn && fn(k, object[k]);
    if (flag === false) return;
  }
}

/**
 * 对象赋值
 * @param object  对象-可传入多个对象
 */
function extend () {
  let arr = arguments, //获取传参集合
    res = {};
  if (arr.length > 0) {
    wx.$each(arr, (i, item) => {
      wx.$each(item, (key, val) => {
        res[key] = val;
      })
    })
  }
  return res;
}


wx.$toast = apiPkg._toast;
wx.$getLocation = apiPkg._getLocation;
wx.$each = each;
wx.$extend = extend;
